#include <fs.h>
#include <ipc.h>

unsigned int read_fs(FILE *file, unsigned int offset, unsigned int length, unsigned char *buffer)
{
	if(file->server != 0)
	{
		unsigned int retlength = 0;
		unsigned int readlength = 0;
		struct read_msg *msg = (struct read_msg *)valloc(sizeof(struct read_msg));
		while(length > 0)
		{
			if(length >= MESSAGE_LENGTH)
				readlength = MESSAGE_LENGTH;
			else
				readlength = length;
			length = length - readlength;
			msg->ino = file->ino;
			msg->offset = (unsigned int)(offset + retlength);
			msg->length = readlength;
			setmsg(msg);
			signal(file->server, SIG_READ, 0);
			wait_for_signal(SIG_ACK, file->server);
			getmsg(msg);
			memcopy((void*)((unsigned int)buffer + retlength), &msg->data, msg->length);
			retlength = retlength + msg->length;
		}
		free(msg);			
		return retlength;
	}
	else
		return 0;
}

unsigned int write_fs(FILE *file, unsigned int offset, unsigned int length, unsigned char *buffer)
{
	if(file->server != 0)
	{
		unsigned int retlength = 0;
		unsigned int writelength = 0;
		
		while(length > 0)
		{
			
			if(length > MESSAGE_LENGTH)
				writelength = MESSAGE_LENGTH;
			else
				writelength = length;
			length = length - writelength;

			struct write_msg *msg = (struct write_msg *)valloc(sizeof(struct write_msg));			
			msg->ino = file->ino;
			msg->offset = (unsigned int)(offset + retlength);
			msg->length = writelength;
			printf(" %x", msg);
			memcopy(&msg->data, (void*)((unsigned int)buffer + retlength), msg->length);
			setmsg(msg);
			wait_ack(file->server, SIG_WRITE, 0);
//			wait_for_signal(SIG_ACK, file->server);
			getmsg(msg);
			retlength = retlength + msg->length;
			free(msg);
			printf("f %x", msg);
		}

		return retlength;
	}
	else
		return 0;
}

FILE *open__fs(inode *ino)
{
	if(ino->proc != 0)
		ino->open(ino);
}

void close_fs(inode *ino)
{
	if(ino->proc != 0)
		ino->close(ino);
}

struct dirent *readdir_fs(inode *ino, unsigned int index)
{
	if((ino->flags & FS_DIRECTORY) && (ino->proc != 0))
		return ino->readdir(ino, index);
	else
		return 0;
}

struct inode_st *finddir_fs(inode *ino, char *name)
{
	if((ino->flags & FS_DIRECTORY) && (ino->proc != 0))
		return ino->finddir(ino, name);
	else
		return 0;
}
